package com.ruoyi.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.app.vo.OrderVO;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.oms.entity.Order;
import com.ruoyi.oms.service.IOrderService;
import com.ruoyi.ums.entity.Member;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@Api(tags = "运输安装订单")
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController{

    @Autowired
    private IOrderService orderService;
    @Autowired
    private WxPayService wxService;

    @ApiOperation("创建订单")
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    public ApiResult<String> createOrder(@RequestBody OrderVO vo) {
        Order order = new Order();
        BeanUtils.copyBeanProp(order, vo);
        order.setMemberId(getMember().getId());
        return orderService.createOrder(order, vo.getItems());
    }

    @ApiOperation("创建支付订单")
    @RequestMapping(value = "/createPayOrder", method = RequestMethod.GET)
    public ApiResult<Void> createPayOrder(@RequestParam("orderSn") String orderSn) throws WxPayException {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Order::getOrderSn,orderSn);
        Order order = orderService.getOne(wrapper);

        /**
         * JSAPI V2支付
         * */
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setOutTradeNo(orderSn);
        request.setBody("服务订单支付");
        request.setSpbillCreateIp(IpUtils.getHostIp());
        request.setTotalFee(order.getOrderAmount().multiply(BigDecimal.valueOf(100)).intValue());
        request.setTradeType("JSAPI");
        wxService.unifiedOrder(request);

        return ApiResult.success();
    }

    @ApiOperation("查看订单列表")
    @RequestMapping(value = "/selectOrderList",method = RequestMethod.GET)
    public ApiResult<Page<Order>> selectOrderList(@RequestParam("pageSize")Integer pageSize,
                                                  @RequestParam("pageNum")Integer pageNum){
        Member member = getMember();
        return ApiResult.success(orderService.selectListByMemberId(pageNum,pageSize,member.getId()));
    }
}
